package net.xdclass.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.AliPayConfig;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.service.ProductOrderService;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Classname CallBackController
 * @Description TODO
 * @Date 2022/8/17 11:36
 * @Created by sunhao
 */
@Slf4j
@RestController
@RequestMapping("/api/callback")
public class CallBackController {

  @Autowired
  private ProductOrderService productOrderService;

  /**
   * 支付宝支付回调接口
   */
  @PostMapping("/alipay")
  public String alipayCallBack(HttpServletRequest request, HttpServletResponse response){
    Map<String, String> requestMap = convertRequestParamsToMap(request);
    log.info("支付宝返回结果{}",requestMap);
    try {
      boolean signVerified = AlipaySignature.rsaCheckV1(requestMap, AliPayConfig.PUBLICKEY, AliPayConfig.CHARSET, AliPayConfig.SIGNTYPE);
      if(signVerified){
       JsonData jsonData =  productOrderService.handlerOrderCallBack(ProductOrderPayTypeEnum.ALIPAY,requestMap);
       if(jsonData.getCode() == 0){
         return "success";
       }
      }
    } catch (AlipayApiException e) {
      log.info("支付宝回调验签失败:异常:{},参数:{}",e,requestMap);
    }
    return "failure";
  }


  /**
   * 将request中的参数转换成Map
   * @param request
   * @return
   */
  private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
    Map<String, String> paramsMap = new HashMap<>(16);
    Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> entry : entrySet) {
      String name = entry.getKey();
      String[] values = entry.getValue();
      int size = values.length;
      if (size == 1) {
        paramsMap.put(name, values[0]);
      } else {
        paramsMap.put(name, "");
      }
    }
    return paramsMap;
  }
}
